<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <!-- 搜索区域 -->
      <a-form layout="inline" @keyup.enter.native="getList">
        <a-row :gutter="24">
          <a-col :md="6" :sm="6">
            <a-form-item label="代理名称" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 1}">
              <a-input placeholder="请输入代理名称" v-model="queryParam.realname"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="6">
            <a-form-item label="联系方式" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 1}">
              <a-input placeholder="请输入联系方式" v-model="queryParam.phone"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="6">
            <a-button type="primary" @click="getList">查询</a-button>
            <a-button style="margin-left: 8px" @click="searchReset">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 按钮操作区 -->
    <section class="button-group">
      <a-button @click="addAgent" type="primary" :loading="addloading">新增</a-button>
    </section>
    <section class="table">
      <a-table ref="table" size="middle" bordered rowKey="id" :columns="columns" :pagination="ipagination"
        :dataSource="agentList" @change="changePage" :loading="loading">
        <span slot="action" slot-scope="record">
          <a @click="toShowDetails(record)">查看详情</a>
          <a-divider type="vertical" />
          <a @click="editAgent(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="changeService(record)">修改密码</a>
        </span>
      </a-table>
    </section>
    <!-- 新建弹窗 -->
    <a-modal :title="boxTitle" :visible="showAdd" :footer="false" width="40%" :closable="true" @cancel="onClose">
      <section class="add-box">
        <a-form-model :label-col="labelCol" :model="newAgent" ref="addForm" :wrapper-col="wrapperCol" :rules="addRules">
          <a-form-model-item label="账号" :required="true" prop="username" v-if="isNew">
            <a-input v-model="newAgent.username" placeholder="请输入代理账号" />
          </a-form-model-item>
          <a-form-model-item label="账号" v-if="!isNew">
            <label>{{newAgent.username}}</label>
          </a-form-model-item>
          <a-form-model-item label="密码" :required="true" prop="password" v-if="isNew">
            <a-input-password v-model="newAgent.password" placeholder="请输入密码" />
          </a-form-model-item>
          <a-form-model-item label="代理名称" :required="true" prop="realname" v-if="isNew">
            <a-input v-model="newAgent.realname" placeholder="请输入代理名称" />
          </a-form-model-item>
          <a-form-model-item label="代理名称" v-if="!isNew">
            <label>{{newAgent.realname}}</label>
          </a-form-model-item>
          <a-form-model-item label="管理区域" prop="provinceId" v-if="isNew">
            <a-select type="list_multi" show-search :filter-option="filterOption" v-model="newAgent.provinceId"
              placeholder="请选择所属省份" @change="changeProvince">
              <a-select-option v-for="(i,index) in provinceList" :value="i.id" :key="index">
                {{i.name}}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label=" " prop="cityId" v-if="isNew">
            <a-select type="list_multi" show-search :filter-option="filterOption" v-model="newAgent.cityId"
              placeholder="请选择所属城市" @change="changeCity">
              <a-select-option v-for="(i,index) in cityList" :value="i.id" :key="index">
                {{i.name}}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="管理区域" v-if="!isNew">
            <label>{{newAgent.cityName}}</label>
          </a-form-model-item>
          <a-form-model-item label="联系方式" :required="true" prop="phone">
            <a-input v-model="newAgent.phone" placeholder="请输入联系方式" />
          </a-form-model-item>
          <a-form-model-item label="平台抽成比例" :required="true" prop="systemPct">
            <a-input-number v-model="newAgent.systemPct" placeholder="佣金比例" style="width: 50%" />
            <label style="margin-left: 10px">%</label>
          </a-form-model-item>
          <a-form-model-item label="支付宝姓名" :required="true" prop="aliName">
            <a-input v-model="newAgent.aliName" placeholder="请输入支付宝姓名" />
          </a-form-model-item>
          <a-form-model-item label="支付宝账号" :required="true" prop="aliAccount">
            <a-input v-model="newAgent.aliAccount" placeholder="请输入支付宝账号" />
          </a-form-model-item>
        </a-form-model>
        <section class="btn-group">
          <a-button type="primary" :loading="saveLoading" @click="saveThis">保存</a-button>
          <a-button @click="onClose">取消</a-button>
        </section>
      </section>
    </a-modal>
    <!-- 修改密码弹窗 -->
    <a-modal :title="boxTitle" :visible="showChange" :footer="false" width="40%" :closable="true" @cancel="onClose">
      <section class="add-box">
        <a-form-model :label-col="labelCol" :model="newAgent" ref="passwordForm" :wrapper-col="wrapperCol"
          :rules="changeRules">
          <a-form-model-item label="密码" :required="true" prop="password">
            <a-input-password v-model="newAgent.password" placeholder="请输入新密码" />
          </a-form-model-item>
        </a-form-model>
        <section class="btn-group">
          <a-button type="primary" :loading="saveLoading" @click="changePassword">保存</a-button>
          <a-button @click="onClose">取消</a-button>
        </section>
      </section>
    </a-modal>
    <!-- 详情弹窗 -->
    <a-modal title="代理详情" :visible="showDetails" :footer="false" width="40%" :closable="true" @cancel="onClose">
      <section class="add-box">
        <a-form-model :label-col="labelCol" :model="agentDetails" :wrapper-col="wrapperCol" :rules="addRules">
          <a-form-model-item label="账号">
            <label>{{agentDetails.username}}</label>
          </a-form-model-item>
          <a-form-model-item label="代理名称">
            <label>{{agentDetails.realname}}</label>
          </a-form-model-item>
          <a-form-model-item label="联系方式">
            <label>{{agentDetails.phone}}</label>
          </a-form-model-item>
          <a-form-model-item label="管理区域">
            <label>{{agentDetails.cityName}}</label>
          </a-form-model-item>
          <a-form-model-item label="平台抽成比例">
            <label>{{agentDetails.systemPct}}%</label>
          </a-form-model-item>
          <a-form-model-item label="支付宝姓名">
            <label>{{agentDetails.aliName}}</label>
          </a-form-model-item>
          <a-form-model-item label="支付宝账号">
            <label>{{agentDetails.aliAccount}}</label>
          </a-form-model-item>
        </a-form-model>
      </section>
    </a-modal>
  </a-card>
</template>

<script>
  import {
    ACCESS_TOKEN
  } from "@/store/mutation-types"
  import Vue from 'vue'
  import {
    postAction,
    getAction,
    putAction
  } from '@/api/manage'
  export default {
    name: 'AgentsList',
    data() {
      return {
        saveLoading: false,
        addloading: false,
        detailsloading: false,
        editloading: false,
        isNew: false,
        boxTitle: '',
        showChange: false,
        queryParam: {
          realname: '',
          phone: '',
          pageNo: '',
          pageSize: 10
        },
        agentDetails: '',
        showDetails: false,
        labelCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 6
          },
        },
        wrapperCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 16
          },
        },
        showAdd: false,
        agentList: [],
        newAgent: {},
        selectedRowKeysArrey: [],
        provinceList: [],
        cityList: [],
        changeRules: {
          password: [{
            required: true,
            message: '请输入密码！',
            // 触发器可以同时用blur和change
            trigger: ['change', 'blur']
          }],
        },
        addRules: {
          username: [{
            required: true,
            message: '请输入账户名!',
            trigger: ['change', 'blur']
          }],
          password: [{
            validator: (rule, value, callback) => {
              if (this.isNew) {
                if (value) {
                  return true;
                } else {
                  return false;
                }
              } else {
                return true;
              }
            },
            message: '请输入密码！',
            // 触发器可以同时用blur和change
            trigger: ['change', 'blur']
          }],
          systemPct: [{
              required: true,
              message: '请输入平台抽成比例!',
              trigger: ['change', 'blur']
            },
            {
              pattern: /^([0-9]{1,2}|100)$/,
              message: '请输入0-10整数',
              trigger: ['change', 'blur']
            },
            {
              validator: (rule, value, callback) => {
                if (Number(value) > 10) {
                  return false
                } else {
                  return true
                }
              },
              message: '"平台抽成比例不超过10！"',
              // 触发器可以同时用blur和change
              trigger: ['change', 'blur']
            }
          ],
          aliAccount: [{
            required: true,
            message: '请输入支付宝账号!',
            trigger: ['change', 'blur']
          }],
          aliName: [{
            required: true,
            message: '请输入支付宝姓名!',
            trigger: ['change', 'blur']
          }],
          realname: [{
            required: true,
            message: '请输入代理名称!',
            trigger: ['change', 'blur']
          }],
          provinceId: [{
            required: true,
            message: '请选择省份!',
            trigger: ['change', 'blur']
          }],
          cityId: [{
            required: true,
            message: '请选择城市!',
            trigger: ['change', 'blur']
          }],
          phone: [{
              required: true,
              message: '请输入联系方式!',
              trigger: ['change', 'blur']
            },
            {
              pattern: /^1(3|4|5|6|7|8|9)\d{9}$/,
              message: '请输入正确手机号',
              trigger: ['change', 'blur']
            }
          ],
        },
        columns: [{
            title: '用户名',
            align: "center",
            dataIndex: 'username'
          },
          {
            title: '代理名称',
            align: "center",
            dataIndex: 'realname'
          },
          {
            title: '联系方式',
            align: "center",
            dataIndex: 'phone'
          },
          {
            title: '管理区域',
            align: "center",
            dataIndex: 'cityName'
          },
          {
            title: '抽成比例',
            align: "center",
            dataIndex: 'systemPct',
            customRender: (value, row, index) => {
              let obj
              if (value) {
                obj = value + '%';
              }
              return obj;
            }
          },
          {
            title: '支付宝姓名',
            align: "center",
            dataIndex: 'aliName'
          },
          {
            title: '支付宝账号',
            align: "center",
            dataIndex: 'aliAccount'
          }, {
            title: '操作',
            dataIndex: '',
            key: 'x',
            scopedSlots: {
              customRender: 'action'
            }
          },
        ],
        ipagination: {
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        loading: false,
        chooseAgent: '',
        headers: {},
        url: {
          list: "/sys/user/getBranchUser",
          parentList: '/sys/user/findProvince',
          cityList: '/sys/user/findCity',
          edit: '/sys/user/updateBranchUser',
          add: '/sys/user/addBranchUser',
          changePassword:"/sys/user/changePassword"
        },
      }
    },
    created() {
      const token = Vue.ls.get(ACCESS_TOKEN);
      this.headers = {
        "X-Access-Token": token
      }
      this.getList();
    },
    methods: {
      // 代理列表改变分页
      changePage(pagination) {
        this.queryParam.pageNo = pagination.current;
        this.queryParam.pageSize = pagination.pageSize;
        this.getList();
      },
      // 获取列表
      getList() {
        this.loading = true;
        getAction(this.url.list, this.queryParam).then(res => {
          console.log(res);
           this.loading = false;
          if (res.success) {
            this.agentList = res.result.records;
            this.ipagination.total = res.result.total;
            this.selectedRowKeysArrey = [];
            this.chooseAgent = '';
          }
        }).finally(() => {
          this.loading = false
        })
      },
      // 选择省份
      changeProvince(e) {
        console.log(e)
        getAction(this.url.cityList, {
          provinceId: e
        }).then(res => {
          console.log(res);
          if (res.success) {
            this.cityList = res.result;
          }
        }).finally(() => {
          this.loading = false
        })
      },
      // 选择城市
      changeCity(e) {
        this.cityList.forEach((item) => {
          if (item.id == e) {
            this.newAgent.cityName = item.name
          }
        })
      },
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      // 显示详情
      toShowDetails(e) {
        this.agentDetails = e;
        this.showDetails = true;
      },
      onClose() {
        this.showAdd = false;
        this.showDetails = false;
        this.showAllot = false;
        this.showLogin = false;
        this.showChange = false;
      },
      //重置
      searchReset() {
        this.selectedRowKeysArrey = [];
        this.queryParam = {
          realname: '',
          phone: '',
          pageNo: this.queryParam.pageNo,
          pageSize: this.queryParam.pageSize
        }
      },
      // 修改密码
      changePassword(){
        this.$refs.passwordForm.validate(valid => {
          if (valid) {
            this.saveLoading = true;
            putAction(this.url.changePassword,{
              username:this.newAgent.username,
              password:this.newAgent.password
            }).then(res => {
              console.log(res);
              this.saveLoading = false;
              if (res.success) {
                this.$message.success(res.message);
                this.showChange = false;
                this.getList();
              } else {
                this.$message.error(res.message)
              }
            })
          }
        })
      },
      // 关闭抽屉
      afterVisibleChange() {
        // this.selectedRowKeysArrey = [];
        // this.newPassword = {};
        // this.queryParam = {
        //   createStartTime: '',
        //   createEndTime: '',
        //   agentName: '',
        //   degree: '',
        //   realname: '',
        //   phone: '',
        //   signingMethod: '',
        //   pageNo: this.queryParam.pageNo,
        //   pageSize: this.queryParam.pageSize
        // }
        // // showAdd = true 表示打开新增代理对象框，此时刷新列表
        // this.getList();
      },
      // 编辑代理商
      editAgent(e) {
        this.editloading = true;
        this.newAgent = e;
        getAction(this.url.parentList).then(res => {
          console.log(res);
          this.addloading = false;
          if (res.success) {
            this.provinceList = res.result;
            this.isNew = false;
            this.showAdd = true;
            if (this.$refs.addForm) {
              this.$refs.addForm.clearValidate();
            }
            this.boxTitle = "编辑代理";
          }
        })
      },
      changeService(e){
        this.newAgent=e;
        this.showChange=true;
      },
      // 新增代理商
      addAgent() {
        getAction(this.url.parentList).then(res => {
          console.log(res);
          if (res.success) {
            this.showAdd = true;
            if (this.$refs.addForm) {
              this.$refs.addForm.clearValidate();
            }
            this.provinceList = res.result;
            this.isNew = true;
            this.newAgent = {}
            this.boxTitle = "新增代理"
          }
        });
      },
      // 保存代理商
      saveThis() {
        console.log(this.newAgent);
        let url;
        if (this.isNew) {
          url = this.url.add
        } else {
          url = this.url.edit
        }
        this.$refs.addForm.validate(valid => {
          if (valid) {
            this.saveLoading = true;
            postAction(url, this.newAgent).then(res => {
              console.log(res);
              this.saveLoading = false;
              if (res.success) {
                this.$message.success(res.message);
                this.showAdd = false;
                this.getList();
              } else {
                this.$message.error(res.message)
              }
            })
          }
        })
      }
    }
  }
</script>
<style scoped>
  .button-group button {
    margin-right: 10px;
  }

  .time-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
  }

  .table {
    margin-top: 20px;
  }

  .time-box span {
    min-width: 0 !important;
  }

  .btn-group {
    display: flex;
    justify-content: center;
  }

  .btn-group button {
    margin-right: 10px;
  }
</style>